package com.struts2.action;

import java.util.ArrayList;


import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.struts2.model.CartItem;
import com.struts2.service.CartService;

public class CartAction extends ActionSupport implements
		ModelDriven<CartItem>, SessionAware {

	private static final long serialVersionUID = 1L;
	
	private CartItem cartItem = new CartItem();
	private List<CartItem> cart = new ArrayList<>();
	private CartService cartService = new CartService();
	
	@SuppressWarnings("unchecked")
	public int getAmount () {
		if (session.get("cart") != null) {
			cart = (List<CartItem>) session.get("cart");
		}
		return cartService.getTotalAmount(cart);
	}
	
	public List<CartItem> getCart() {
		return cart;
	}

	public void setCart(List<CartItem> cart) {
		this.cart = cart;
	}

	public CartService getCartService() {
		return cartService;
	}

	public void setCartService(CartService cartService) {
		this.cartService = cartService;
	}

	public CartItem getCartItem() {
		return cartItem;
	}

	public void setCartItem(CartItem cartItem) {
		this.cartItem = cartItem;
	}

	// For SessionAware
	private Map<String, Object> session;

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@SuppressWarnings("unchecked")
	public String addToCart() {


		if (cartService.isLeftStock(cartItem)) {
			if (session.get("cart") != null) {
				cart = (List<CartItem>) session.get("cart");
			}
			cart.add(cartItem);
			session.put("cart", cart);
			return SUCCESS;
		}

		return ERROR;
	}

	@SuppressWarnings("unchecked")
	public String delToCart() {

		cart = (List<CartItem>) session.get("cart");
		for (Iterator<CartItem> i = cart.listIterator(); i.hasNext();) {
			CartItem cCartItem = i.next();
			if (cCartItem.getProductItemId() == cartItem.getProductItemId()) {
				i.remove();
			}
		}
		session.put("cart", cart);
		return SUCCESS;
	}

	public void updateToCart(CartItem newCartItems) {
		/*
		 * if (cartService.isLeftStock(newCartItems)) { cart.remove(cartItems);
		 * cart.add(newCartItems); session.put("cart", cart); }
		 */
	}

	public String checkOut() {
		cartService.deductInventory(cart);
		session.remove("cart");
		return SUCCESS;
	}

	@Override
	public CartItem getModel() {
		return cartItem;
	}

}
